package com.hue.gulimail.gulimailproduct.exception;

import com.hue.common.utils.Error;
import com.hue.common.utils.R;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一异常处理
 */
@Component
@RestControllerAdvice(basePackages = "com.hue.gulimail.gulimailproduct.controller")
public class GuliMailException {
    /**
     * 效验参数的异常处理
     *
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R validatorException(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            String message = error.getDefaultMessage();
            String field = error.getField();
            errorMap.put(field, message);
        }
        return R.error(Error.VALIDATOR_ERROR.getCode(), Error.VALIDATOR_ERROR.getMsg()).put("data", errorMap);
    }

    /**
     * 捕获最大的异常
     *
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public R exception(Exception exception) {
        String message = exception.getMessage();
        return R.error(Error.UNKNOWN_ERROR.getCode(), Error.UNKNOWN_ERROR.getMsg()).put("data",message);
    }
}
